package controllers

import (
	"2301_press/cache"
	"2301_press/models"
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

var ctx = context.Background()

type PressController struct {
	beego.Controller
}

func (c *PressController) Add() {
	title := c.GetString("title")
	cate := c.GetString("cate")
	if title == "" || cate == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加内容不能为空",
		}
		c.ServeJSON()
		return
	}
	var press models.Press
	press.Title = title
	press.Cate = cate
	err := press.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	presses, _ := press.List()
	jsonData, _ := json.Marshal(presses)
	cache.Rdb.Set(ctx, "press", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}
func (c *PressController) List() {
	cacheData := cache.Rdb.Get(ctx, "novel_list").Val()
	var presses []models.Press
	if cacheData != "" {
		models.DB.Find(&presses)
		jsonData, _ := json.Marshal(presses)
		cache.Rdb.Set(ctx, "novel_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &presses)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "获取成功",
	}
	c.ServeJSON()
	return
}
